package com.ex.util

import java.lang.reflect.Field

class Reflect {


    private var type: Class<*>
    private var obj: Any

    constructor(type: Class<*>) {
        this.type = type
        this.obj = type
    }

    @Suppress("UNCHECKED_CAST")
    fun <T> get(): T = obj as T

    fun set(name: String, value: Any) {
        val f = field0(name)
        f.isAccessible = true
        f.set(obj, value)
    }

    private fun field0(name: String): Field {
        return type.getField(name)
    }

    companion object {

        fun on(clazz: Class<*>): Reflect {
            return Reflect(clazz)
        }

        fun on(obj: Any?): Reflect {

            if (obj == null) {
                return Reflect(type = Object::class.java)
            } else return Reflect(obj.javaClass)
        }

        fun on(clazzName: String): Reflect {

            val t = Class.forName(clazzName)
            return Reflect(t)

        }
    }

}